import { ProductionOrderService } from './order.service';
import { Body, Controller, Post, Get, Res, Headers, Req } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { ADMIN_PREFIX } from '../../admin.constants';
import { AdminUser } from '../../core/decorators/admin-user.decorator';
import i18n from '@main/i18n';
import { format } from 'date-fns';
import { FastifyRequest } from 'fastify';
import { Authorize } from '../../core/decorators/authorize.decorator';

@ApiSecurity(ADMIN_PREFIX)
@ApiTags('工单管理模块')
@Controller('order')
export class ProductionOrderController {
  constructor(private productionOrderService: ProductionOrderService) {}

  @ApiOperation({ summary: '获取工单列表' })
  @ApiOkResponse()
  @Post('list')
  async list(@Body() dto) {
    return await this.productionOrderService.list(dto);
  }

  @ApiOperation({ summary: '通过mac获取获取工单列表' })
  @ApiOkResponse()
  @Post('byMachineCode')
  async getOrderByMachineCode(@Body() dto) {
    return await this.productionOrderService.getOrderByMachineCode(dto);
  }

  @ApiOperation({ summary: '分页获取获取工单列表' })
  @ApiOkResponse()
  @Post('page')
  async page(@Body() dto) {
    const [list, total] = await this.productionOrderService.page(dto);

    return {
      list,
      pagination: {
        total,
        pageNum: dto.pageNum,
        pageSize: dto.pageSize,
      },
    };
  }

  @ApiOperation({ summary: '添加工单' })
  @ApiOkResponse()
  @Post('add')
  async add(
    @Body() dto,
    @Headers('language') languageType,
    @AdminUser() user,
    @Req() req: FastifyRequest
  ) {
    // const result = await this.productionOrderService.isExistKey(data);

    // if (result) {
    //   return IpcErrorException('操作失败，已存在相同的key');
    // }
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;

    await this.productionOrderService.add(dto, languageType, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '更新工单' })
  @ApiOkResponse()
  @Post('update')
  async update(
    @Body() dto,
    @Headers('language') languageType,
    @AdminUser() user,
    @Req() req: FastifyRequest
  ) {
    // const result = await this.productionOrderService.isExistKey(data);

    // if (result) {
    //   return IpcErrorException('操作失败，已存在相同的key');
    // }
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;

    await this.productionOrderService.update(dto, languageType, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '更新调机完成时间' })
  @ApiOkResponse()
  @Post('updateAdjuest')
  async updateAdjuest(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    await this.productionOrderService.updateAdjuest(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '工单设备变更' })
  @ApiOkResponse()
  @Post('updateMachine')
  async updateMachine(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    await this.productionOrderService.updateMachine(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '工单顺序变更' })
  @ApiOkResponse()
  @Post('updatePro')
  async updatePro(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    await this.productionOrderService.updatePro(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '删除工单' })
  @ApiOkResponse()
  @Post('delete')
  async delete(@Body() dto, @AdminUser() user, @Req() req: FastifyRequest) {
    const { mac = '', ip = '', synchostsqlite: syncHostSqlite = '' } = req.headers;
    await this.productionOrderService.delete(dto, user, mac, ip, syncHostSqlite);
  }

  @ApiOperation({ summary: '获取字典表字段列表' })
  @ApiOkResponse()
  @Get('cloums')
  async cloums() {
    return await this.productionOrderService.getColumnsList();
  }

  @ApiOperation({ summary: '通过时间区间获取班次统计信息' })
  @ApiOkResponse()
  @Post('statisticsByShiftTime')
  async statisticsByShiftTime(@Body() dto) {
    return await this.productionOrderService.statisticsByShiftTime(dto);
  }

  @ApiOperation({ summary: '导出工单列表' })
  @ApiOkResponse()
  @Post('export')
  async export(@Body() dto, @Res() res, @Headers('language') languageType) {
    const buffer = await this.productionOrderService.export(dto, languageType);

    const langObj = i18n[languageType]['common']['table'];

    res.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

    res.header(
      'Content-Disposition',
      `attachment; filename=${encodeURIComponent(
        langObj['productionOrder'] + format(new Date(), 'yyyyMMddHHmmss') + '.xlsx'
      )}`
    );

    res.header('Access-Control-Expose-Headers', 'Content-Disposition');

    res.send(buffer);
  }

  @ApiOperation({ summary: '当班生产进度' })
  @ApiOkResponse()
  @Get('onDutyProductionProgress')
  @Authorize()
  async onDutyProductionProgress(@Headers('language') languageType) {
    return await this.productionOrderService.onDutyProductionProgress(languageType);
  }
}
